package com.ui.basic.dao.assembler;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.jsecurity.SecurityUtils;
import org.jsecurity.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.common.basic.base.BaseAssembler;
import com.common.basic.util.FieldSorter;
import com.common.basic.util.Globals;
import com.ui.basic.command.CommandMenu;
import com.ui.basic.ibatis.model.system.TblSMenu;
import com.ui.basic.ibatis.model.system.TblSUser;
import com.ui.basic.listener.UserStream;
import com.ui.basic.resolver.MessageResolver;

@Service("menuAssembler")
public class MenuAssembler implements BaseAssembler<TblSMenu, CommandMenu> {
	private MessageResolver messageResolver;

	@Autowired
	public void setMessageResolver(MessageResolver messageResolver) {
		this.messageResolver = messageResolver;
	}

	private CommandMenu findParent(List<CommandMenu> list, String code) {
		String parentCode = code.substring(0, code.length() - 2);
		for (int i = list.size() - 1; i >= 0; i--) {
			if (parentCode.equals(list.get(i).getCode()))
				return list.get(i);
		}
		return null;
	}

	public CommandMenu toDto(TblSMenu entity) {
		CommandMenu dto = new CommandMenu();
		if (entity != null) {
			dto.setCode(entity.getMenuCode());
			dto.setDescription(entity.getMenuDesc());
			dto.setIcon(entity.getMenuIcon());
			dto.setId(entity.getId());
			dto.setLink(entity.getMenuLink());
			dto.setName(entity.getMenuName());
			dto.setIsView(entity.getMenuViewable());
		}
		return dto;
	}

	@SuppressWarnings("unchecked")
	public List<CommandMenu> toDtoList(List<TblSMenu> listEntity) {
		Subject currentUser = SecurityUtils.getSubject();

		List<CommandMenu> listDto = new ArrayList<CommandMenu>();
		if (listEntity != null) {
			int num = 0;
			Collections.sort(listEntity, new FieldSorter("code", true));
			while (!listEntity.isEmpty()) {
				CommandMenu menu = toDto(listEntity.get(0));
				listEntity.remove(0);
				if (menu.getIsView().booleanValue()
						&& currentUser.isPermitted(menu.getId().toString())) {
					menu.setName(getMenuName(menu.getName()));
					if (menu.getCode().length() > 2
							&& findParent(listDto, menu.getCode()) != null) {
						CommandMenu parent = findParent(listDto, menu.getCode());
						String child = menu.getCode().concat("|").concat(
								String.valueOf(menu.getName().length()));
						parent.getChilds().add(child);
						menu.setPrefix(parent.getPrefix().concat("_").concat(
								String.valueOf(parent.getChilds().size())));
					} else
						menu.setPrefix(String.valueOf(++num));

					listDto.add(menu);
				}
			}
		}
		return listDto;
	}

	public TblSMenu toEntity(CommandMenu dto) {
		TblSMenu entity = new TblSMenu();
		if (dto != null) {
			entity.setMenuCode(dto.getCode());
			entity.setMenuDesc(dto.getDescription());
			entity.setMenuIcon(dto.getIcon());
			entity.setId(dto.getId());
			entity.setMenuLink(dto.getLink());
			entity.setMenuName(dto.getName());
			entity.setMenuViewable(dto.getIsView());
		}
		return entity;
	}

	@SuppressWarnings("unchecked")
	public boolean validateLinkRequest(List<TblSMenu> listEntity,
			String strReqLink) {
		Subject currentUser = SecurityUtils.getSubject();

		if (listEntity != null) {
			for (Iterator iterator = listEntity.iterator(); iterator.hasNext();) {
				TblSMenu tblMenu = (TblSMenu) iterator.next();
				if (tblMenu.getMenuLink().equals(strReqLink)) {
					currentUser.getSession().setAttribute("PAGE_TITLE", messageResolver
							.getMessage(tblMenu.getMenuName()));
					return currentUser.isPermitted(tblMenu.getId().toString());
				}
			}
		}
		return false;
	}

	public Object getUserFromJSecurity() {
		TblSUser user = (TblSUser) SecurityUtils.getSubject().getSession().getAttribute(Globals.USER_KEY);
		UserStream userstream = (UserStream) SecurityUtils.getSubject().getSession().getAttribute(Globals.USERSTREAM);
		if(user!=null && userstream!=null)
			userstream.updateUser(user);
		return user;
	}

	private String getMenuName(String menuName) {
		return messageResolver.getMessage(menuName);
	}

	public String getStringMenuView(List<TblSMenu> listEntity) {
		Subject currentUser = SecurityUtils.getSubject();
		StringBuffer strListMenuCode = new StringBuffer("");
		String result = "";

		if (listEntity != null) {
			for (TblSMenu tblMenu: listEntity) {
				if (tblMenu.getMenuViewable().booleanValue() && currentUser.isPermitted(tblMenu.getId().toString())) {
					strListMenuCode.append(tblMenu.getMenuCode());
					strListMenuCode.append(",");
				}
			}
			result = strListMenuCode.toString();
			if(result.endsWith(","))
				result = result.substring(0, result.lastIndexOf(","));
		}
		return result;
	}
}
